﻿using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;

namespace 父窗口载入子窗口
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        [DllImport("user32.dll", EntryPoint = "SetParent")]
        public extern static IntPtr SetParent(IntPtr childPtr, IntPtr parentPtr);

        public MainWindow()
        {
            InitializeComponent();
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            Application.Current.Shutdown();
        }

        private void OpenChildWindow_Click(object sender, RoutedEventArgs e)
        {
            // 将子窗口的内容嵌入父窗口的 ContentControl 中
            ChildWindow childWindow = new ChildWindow();


            ChidStackPanel.Children.Add(new Button()
            {
                Width = 200,
                Height = 40,
                Content = "动态创建的按钮",
                Margin = new Thickness(0, 5, 0, 0),
            });

        }

        /// <summary>
        /// 使用window32 API 的形式将子窗体加载到父窗体
        /// </summary>
        public void Win32ApiSetWindowChidToParent()
        {
            ChildWindow childWindow = new ChildWindow();

            WindowInteropHelper parentHelper = new WindowInteropHelper(this);
            WindowInteropHelper childHelper = new WindowInteropHelper(childWindow);

            childWindow.Show();
            SetParent(childHelper.Handle, parentHelper.Handle);

            childWindow.WindowState = WindowState.Maximized; //窗口最大化
            childWindow.WindowStyle = WindowStyle.None;

        }
    }
}
